package reaction.europarl;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.apache.lucene.analysis.WhitespaceAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;

import reaction.europarl.queries.QueryEL;
import reaction.europarl.queries.candidates.Candidate;

public class Ranking {
	
	public static List<QueryEL> Testqueries = new LinkedList<QueryEL>();
	public static List<QueryEL> Trainqueries = new LinkedList<QueryEL>();
		
	public static void extractFeatures(List<QueryEL> train_queries, boolean trainning) throws IOException, ParseException {
		
		int processed = 0;
		boolean foundCorrecEntity = false;
		
		for (QueryEL q : train_queries) {
			
			System.out.print(q.query_id);
			
			for (Candidate c : q.candidates) {
				System.out.print(".");
				c.extractFeatures(q);
				if (c.features.correct_answer && trainning) {
					foundCorrecEntity = true;
				}
			}
			
			if ( trainning && ((!foundCorrecEntity && !(q.URL_answer.startsWith("NIL"))) || ( !(q.URL_answer.startsWith("NIL")) && q.candidates.size()==0)) )
				getCorrectAnswer(q);
			
			processed++;
			System.out.println("(" + processed + "/" + train_queries.size() + ")" );
		}		
	}	

	
	/*
	 *  if answer entity is not part of the retrieved entities and correct answer is not NIL, 
	 *  retrieve answer entity from KB and extract features
	 */
	
	public static void getCorrectAnswer(QueryEL q) throws ParseException, IOException {
				
		QueryParser queryParser = new QueryParser(org.apache.lucene.util.Version.LUCENE_35,"URL", new WhitespaceAnalyzer());
		ScoreDoc[] scoreDocs = null;
		String[] answer_parts = q.URL_answer.split("/");
		String queryS = "URL:" + answer_parts[answer_parts.length-1];		
		Query query = queryParser.parse(queryS);
		
		TopDocs docs = Definitions.wikipediaSearcher.search(query, 1);				
		scoreDocs = docs.scoreDocs;
		
		if (docs.totalHits != 0) {
		
			Document doc = Definitions.wikipediaSearcher.doc(scoreDocs[0].doc);
			float lucene_score = scoreDocs[0].score;
			
			Candidate c = new Candidate(doc,lucene_score);
			q.candidates.add(c);
			System.out.print(".");
			c.extractFeatures(q);
		}
	}

}
